/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.*;
import java.util.Random;

/**
 * <p>Project: app2022 - Ex9
 * <p>Powered by webrx On 2022-01-19 14:31:43
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex9 {
    final static int DEFAULT_BUFFER_SIZE = 1024 * 20;

    public static void main(String[] args) {
        String f = "u.txt";
        //建立文件 c:/app2022/u.txt
        try (var w = new BufferedWriter(new FileWriter(f, true))) {
            Random rand = new Random();
            w.write(String.format("%07d[%tF %<tT]%n", rand.nextInt(1, 99999), System.currentTimeMillis()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //读取文件
        try (var r = new BufferedReader(new FileReader(f))) {
            r.lines().forEach(System.out::println);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //文件复制 u.txt 复制到 u2.txt
        try (var is = new BufferedInputStream(new FileInputStream(f)); var out = new FileOutputStream("u3.txt")) {
            //is.transferTo(new FileOutputStream("u2.txt"));

            long transferred = 0;
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int read;
            while ((read = is.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {
                out.write(buffer, 0, read);
                transferred += read;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        var file = new File(f);
        //更名文件
        var fn = file.getName();
        fn = "u20220119.txt";
        //更名（剪切，粘贴，移动文件）u.txt 换了 u20220119.txt
        //file.renameTo(new File(fn));

        //file.renameTo(new File("c:/my2022.txt"));


        //删除文件
        if (file.exists()) {
            //file.delete();
        }
    }


}
